import styles from "./Index.module.less";
import FontIcon from "@/components/public/fontIcon/Index";
import { useDispatch, useSelector } from "react-redux";
import type { RootState } from "@/store";
import { setCollapsed } from "@/store/menu";
import Breadcrumb from "../breadcrumb/Index";
import DropdownList from "../dropdownList/Index";
import RightClickPopup from "@/components/public/RightClickPopup/Index";
import { Tag } from "antd";
import { useEffect, useRef, useState } from "react";
import { useLocation, useNavigate } from "react-router-dom";
import { getMatches } from "@/router";

type RightClickPopupProps = React.ComponentProps<typeof RightClickPopup> & { path?: string };

export default function Index() {
  const dispatch = useDispatch();
  const navigate = useNavigate();
  const location = useLocation();

  /** 当前活跃的路由 */
  const [activeRoute, setActiveRoute] = useState<string>("/");
  /** tag列表 */
  const [tagList, setTagList] = useState<any>([]);
  useEffect(() => {
    const routeInfo = getMatches(location.pathname);
    if (routeInfo) {
      const route = routeInfo.at(-1)?.route;
      setActiveRoute(route?.path || "/");
      if (
        route?.path &&
        route?.path != "/home" &&
        route?.path != "/" &&
        tagList.findIndex((item: any) => item.path == route?.path) == -1
      ) {
        const list = [
          ...tagList,
          {
            name: route?.handle?.meta?.title || "",
            path: route?.path,
          },
        ];
        setTagList(list);
      }
    }
  }, [location]);

  const collapsed = useSelector((state: RootState) => state.menu.collapsed);
  const handleOpenCollapsed = () => {
    dispatch(setCollapsed(!collapsed));
  };

  /** 事件列表 */
  const getContextMenuList = (isHome?: boolean) => {
    return [
      {
        key: "1",
        name: "关闭",
        icon: "icon-close",
        onClick: () => {
          const newTagList = tagList.filter((item: any) => item.path != popupRef.current.path);
          setTagList(newTagList);
          let path;
          if (newTagList && newTagList.length > 0) {
            path = newTagList.at(-1)?.path;
          } else {
            path = "/home";
          }
          setActiveRoute(path);
          navigate(path);
        },
      },
      {
        key: "2",
        name: "关闭其他",
        icon: "icon-close",
        onClick: () => {
          const newTagList = tagList.filter((item: any) => item.path == popupRef.current.path);
          setTagList(newTagList);
        },
      },
      {
        key: "3",
        name: "关闭所有",
        icon: "icon-close",
        onClick: () => {
          setTagList([]);
          navigate("/home");
        },
      },
      {
        key: "4",
        name: "刷新",
        icon: "icon-refresh",
        onClick: () => {
          navigate(activeRoute);
        },
      },
    ].filter((item) => {
      if (item.key == "1") {
        return !isHome;
      } else {
        return true;
      }
    });
  };

  /** 右击组件属性 */
  const [popup, setPopup] = useState<RightClickPopupProps>({
    x: 0,
    y: 0,
    show: false,
    list: [],
    path: "",
  });

  /** 方便获取最新 popup */
  const popupRef = useRef(popup);

  // 每次 popup 更新，同步到 ref
  useEffect(() => {
    popupRef.current = popup;
  }, [popup]);

  /** 右击事件 */
  const handleRigthClick = (
    e: React.MouseEvent<HTMLDivElement | HTMLSpanElement>,
    isHome: boolean = false,
    path: string
  ) => {
    e.preventDefault();
    setPopup({
      ...popup,
      list: getContextMenuList(isHome),
      x: e.clientX,
      y: e.clientY,
      show: true,
      path,
    });
  };

  /** 移除右击事件 */
  useEffect(() => {
    const remove = () => {
      setPopup({
        ...popup,
        show: false,
      });
    };
    document.addEventListener("click", remove);
    return () => {
      document.removeEventListener("click", remove);
    };
  }, []);

  return (
    <>
      <div className={`${styles.row} ${styles.top}`}>
        <div className={styles.left}>
          <div
            className={styles.is_collapse}
            onClick={() => {
              handleOpenCollapsed();
            }}>
            {collapsed ? (
              <FontIcon className={styles.icon} name="icon-open" size="20px" />
            ) : (
              <FontIcon className={styles.icon} name="icon-fold-up" size="20px" />
            )}
          </div>

          <Breadcrumb />
        </div>
        <div className={styles.rigth}>
          <DropdownList />
        </div>
      </div>
      <div className={`${styles.row} ${styles.tag}`}>
        <Tag
          closable
          onContextMenu={(event) => handleRigthClick(event, true, "/")}
          color={activeRoute == "/home" ? "processing" : ""}
          onClick={() => navigate("/home")}>
          首页
        </Tag>
        {tagList.map((item: any) => {
          return (
            <Tag
              key={item.path}
              closable
              onContextMenu={(event) => handleRigthClick(event, false, item.path)}
              color={activeRoute == item.path ? "processing" : ""}
              onClick={() => navigate(item.path)}>
              {item.name}
            </Tag>
          );
        })}
      </div>

      <RightClickPopup {...popup} />
    </>
  );
}
